 <?


class CTRLnewsletter extends CONTROL {

	function __construct( $vars ) {
		global $Object;
		
		$this->_addvars( $vars );

		if( $this->action != "list" )
			$Object = $this->create_object();
	}
	
#	New Object.
	function filter_new() {
		global $Object;

		if( $this->parent ) $new = "$('$this->parent').seed([" . $Object->render_core_json() . "], 0);";

		$Object->set( "meta", array( "year"=> date( "Y" ), "theme"=> engine_get( "theme" )), 1 );

		return $new . $this->filter_edit(); 
	}


#	Edit Object.
	function filter_edit() {
		global $DB, $Engine, $Object, $Page;
		
		// vars id
		if( !$this->vars->id ) $this->vars->id = $Object->id;
		
		// mail template
		$mail_settings	= $DB->get_key( "json.object", "ID = " . (int) engine_get( 'mailer.content.default' ), "json" );
		$mail_settings	= json_decode( $mail_settings );
		$template = $Engine->text->get( $mail_settings->html_template, "long", engine_get( 'lang.master' ));
		if( count( explode( '</style>', $template ) >= 1 )){
			
			// css
			$styles 	= explode( '<br />', nl2br( array_shift( explode( '</style>', $template ))));
			//$styles 	= explode( '\n', array_shift( explode( '</style>', $template )));
			$counter	= 0;
			foreach( $styles as $style ) {
				$style = substr( str_replace( array("\r\n", "\r", "\n"), " ", $style ), 1);
				if( $counter > 0 && substr( $style, 0, 1 ) != '@' && !empty( $style )) {
					//echo '#lightbox_textid ' . $style;
					$stylers .= '.field ' . $style . ' ';
				}
				$counter++;
			}
			//$stylers = implode( '\n', $stylers );
			
			// html 
			$template = '<style type="text/css">' . $stylers . '</style>' . array_pop( explode( '</style>', $template ));
			//$template = array_pop( explode( '</style>', $template ));
		}
				
		// page
		$Page = new PAGE((int) $mail_settings->location );

		// replacers
		$replacers = array(
			"%date%"	=> (( $Object->get( 'flog' )) ? date( "d.m Y", strtotime( $Object->get( "flog" ))) : date( "d.m Y" )),
			"%issue%"	=> (( $Object->id ) ? $Object->id : 'xxx' ),
			"%title%"	=> (( $Object->get( "name" )) ? $this->title = $Object->get( "name" ) : '' ),
			"%style%"	=> PUBLIC_THEME . "/mailer",
			"%url"		=> $Page->url( "?letterid=". (( $Object->id ) ? $Object->id : 'xxx' )),
			"%year%"	=> (( $Object->get( 'flog' )) ? date( "Y", strtotime( $Object->get( "flog" ))) : date( "Y" ))
		);
		
		// side replacers (images)
		if( $Object->hasMedia() && $media = $Object->media->reference( "media.img" )) {
			foreach ( $media as $el ) $side[] = "<img src='". engine_get( "url" ) ."/public.img?id=$el&sze={$mail_settings->imgsze}' />";
			$replacers[ "%side%" ] = implode( "\n", $side );
		} else {
			$replacers[ "%side%" ] = "<i>no images yet..</i>";
		}
		
		// mods in mail template
		if( $mail_settings->mods ) {
		
			$modules	= array();
			$mods 		= $mail_settings->mods;
			$modcon		= new MOD_CONSTRUCT();
			foreach((array) $mods as $column => $ids ) {
				
				if( count( $ids )) foreach( $ids as $id ) {
			
					$Mod = $modcon->call(( int ) $id );
					$modules[ "%mods:$column%" ] .= utf8_encode( $Mod->output());
				}
				$replacers[ "%mods:$column%" ] = $modules[ "%mods:$column%" ];
			}
		}
				
		// text replace
		$cont	= array();
		foreach( $Engine->text->filter( $Object->get( "textid" ), 'long' ) as $language => $text ) {
			
			$wrapper = array( "wrap" => str_replace( array_keys( $replacers ), array_values( $replacers ), $template ));
			
			$volume = str_replace( '%content%', $text, $template );
			$volume	= str_replace( array_keys( $replacers ), array_values( $replacers ), $volume );
			$cont[ $language ]	= $volume;
			
			$lang_values[ $language ] = utf8_encode( $text );
		}		
						
		$type = $this->vars->type;
		
		$open = $done = 0;
		if( $done = count( $DB->reference( "newsletter", (int) $this->vars->id, "user", null, "social" ))) {
			$open = (int) $DB->count( "user", "active && lang = '". LANG ."'" ) - $done;
			if( $open < 0 ) $open = 0;
		}
		
		return "
		ref.seed([
			
			new Element( 'h1' ).update( \"Beheer $type '". (( $Object->get( "nameid" ) )? $Engine->text->get( $Object->get( "nameid" ) ) : $Object->id ) . "'\" ),
			new Textfield({ descr:'header $type', type:'$type', parentid:{$Object->id}, textid:". $Object->get( "nameid" ) .", values:". json_encode( $Engine->text->filter( $Object->get( "nameid" ) )) ." }),
			new Lightboxfield({ descr:'text $type', type:'$type', parentid:{$Object->id}, textid:". $Object->get( "textid" ) .", contenteditable:'false', wrapper:" . json_encode( $wrapper ) . ", values:". json_encode( $lang_values ) ." }),
			new Dropbox({ descr:'Beelden', type:'media.img', parenttype:'$type', action:'win', blank:'add image', id:{$Object->id}, uptype:'media', floats:". $this->filter_media( 'media.img' ) ." }),
			new Options({ descr:'Opties', floats: [
				new Ajxfield({ type:'$type', descr:'weergegeven datum', objid:{$Object->id}, field:'flog', value:'{$Object->get('flog')}', extend:'cal' })
			]}),
			new Options({ descr:'Publiceren', active:1, floats: [
				new Element( 'span' ).update( '$open te bereiken gebruikers ($done verzonden)' ),
				new Shift({ type:'$type', descr:'Publiceerbaar', value:{$Object->get( 'active' )}, field:'active', objid:{$Object->id} }),
				new Button({ action: 'example', type: 'newsletter', descr: 'verzend voorbeeld', id:{$Object->id}}),
				new Button({ action: 'publish', type: 'newsletter', descr: 'start publicatie', buffer: 'publicatie gestart', id:{$Object->id}})
			]})
		]);";

	}


	
#	Render media floats
	function filter_media( $objtype ) {
		global $DB, $Object;
		
		$result = array();
		
		if( $images = $Object->media->filter( $objtype ))
			foreach( $images as $img ) {
				$result[] = array( "id"=> $img['ID'], "type"=> $objtype, "name"=> $objtype, "list"=> array( $img['ID'], json_decode( $img[ 'meta' ])->raw ));
			}
		
		return json_encode( $result );
	}
	

#	Publish example.
	function filter_example() {
		global $Engine;
		
		
		
		$Letter = new MAIL( "html" );
		
		//// LANG SHOULD BE EDITABLE!!!
		$example = $Letter->generate_newsletter( $this->vars->id, "nl" );
		$Letter->send_single(( int ) $Engine->user( 'ID' ));
		
		return $this->comment( "Verzonden naar ". $Engine->user( "mail" ));

	}

#	Publish all.
	function filter_publish() {
		global $DB, $Engine;
		
		//// LANG SHOULD BE EDITABLE!!!
		$Letter	= new MAIL( "html" );
		$Letter->generate_newsletter( $this->vars->id, "nl" );
		
		if( !$done = $DB->reference( "newsletter", (int) $this->vars->id, "user", null, "social" )) $done = array( 0 );

		if( $count = $Letter->send( "ID not in( ". implode( ",", $done ) ." ) && active && lang = '". LANG ."' order by ID", true ))

				$comment = "Publicatie $count nieuwsbrieven succesvol!";
		else	$comment = "Geen resultaat (alreeds verzonden)";
		
		return $this->comment( $comment );
	}
	
}